import React, { Component } from 'react';
import {
  View,
  Text,
  TextInput,
  Button,
  StyleSheet,
  ScrollView,
  Image,
  TouchableOpacity,
  ImageBackground,
  ToastAndroid,
  DeviceEventEmitter,
} from 'react-native';
import * as ImagePicker from 'react-native-image-picker';
import Icon from 'react-native-vector-icons/AntDesign';
import { Picker } from '@react-native-picker/picker';
import DocumentPicker, {
  DirectoryPickerResponse,
  DocumentPickerResponse,
  isCancel,
  isInProgress,
  types,
} from 'react-native-document-picker';

import Loading from '../../compenent/Loading';
import {
  DOMAIN_URL,
  lessonAdd,
  lessonUpdate,
  uploadFile,
} from '../../../util/api';
import { DateTimePickerAndroid } from '@react-native-community/datetimepicker';
import moment, { months } from 'moment';
import { PAGENAME } from '../../../util/PageName';
import { style } from '../../../theme';
import { FILE_TYPE } from '../../../util/global';
import DeleteIcon from '../../compenent/DeleteIcon';

const MEDIA_TYPE = [
  {
    name: '文档',
    value: FILE_TYPE.WORD,
  },
  {
    name: '视频',
    value: FILE_TYPE.VIDEO,
  },
  {
    name: 'PDF',
    value: FILE_TYPE.PDF,
  },

  {
    name: '音频',
    value: FILE_TYPE.AUDIO,
  },

];

class LessonEditScreen extends Component {
  constructor(props) {
    super(props);
    console.log(props.route.params);
    console.log(props.route.params?.data);
    this.state = {
      data: props.route.params?.data,
      name: props.route.params?.data.name || '',
      description: props.route.params?.data.description || '',
      score: `${props.route.params?.data.score || 2}`,
      images: props.route.params?.data.frontCoverDetail || null,
      mediaType: FILE_TYPE.WORD,
      attachment: props.route.params?.data.attachmentDetail || null,
      endTime: moment(props.route.params?.data.endTime).toDate() || new Date(),
      // 'descriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescription',
      // score: '2',
      // images: [],
      // endTime: new Date(),
      loading: false,
    };
  }

  pickImage = () => {
    ImagePicker.launchImageLibrary(
      { mediaType: 'photo', selectionLimit: 5 },
      response => {
        if (!response.didCancel) {
          this.setState({
            images: response.assets?.map(asset => asset)[0],
          });
        }
      },
    );
  };
  submitData = async () => {
    this.setState({ loading: true });
    // let imgs: any[] = this.state.preImages.map(v => v.id);
    console.log(this.state.images);
    console.log('upload attachment', this.state.attachment);

    // setTimeout(() => {
    //   this.setState({ loading: false })
    // }, 5000);
    // for (let index = 0; index < this.state.images.length; index++) {
    const element = this.state.images;
    const attachmentFile = this.state.attachment;
    let frontCover, attachment
    element.uri
      ? await uploadFile(
        {
          uri: element.uri, // 替换为实际文件路径
          type: element.type,
          name: element.fileName,
        },
        FILE_TYPE.IMAGE,
      )
        .then(res => {
          console.log(res);
          if (res.code == 0) {
            console.log(`${element} upload success.`);
            frontCover = res.data.id
            // imgs.push();
          } else {
            ToastAndroid.show(`上传失败:${res.msg}`, 2000);
          }
        })
        .catch(e => {
          console.log(e);
          ToastAndroid.show(`上传失败:${e}`, 2000);
        })
      : frontCover = element.id



    attachmentFile.uri
      ? await uploadFile(
        // {
        //   uri: this.state.attachment.uri, // 替换为实际文件路径
        //   type: this.state.attachment.type,
        //   name: this.state.attachment.name,
        // },
        this.state.attachment,
        this.state.mediaType || FILE_TYPE.WORD,
      )
        .then(res => {
          console.log(res);
          if (res.code == 0) {
            console.log(`upload success ${this.state.attachment}`);
            // imgs.push(res.data.id);
            attachment = res.data.id
          } else {
            ToastAndroid.show(`上传失败:${res.msg}`, 2000);
          }
        })
        .catch(e => {
          console.log(e);
          ToastAndroid.show(`上传失败:${e}`, 2000);
        })
      : attachment = attachmentFile.id
    // this.setState({loading: false});
    // if (imgs.length > 0) {
    if (this.state.data?.id) {
      // 编辑
      const { data } = this.state;
      data.name = this.state.name;
      data.description = this.state.description;
      data.endTime = moment(this.state.endTime).format('YYYY-MM-DD HH:MM:SS');
      data.frontCover = frontCover;
      data.attachment = attachment;
      data.score = Number.parseInt(this.state.score, 10);
      data.delFlag = '0'

      lessonUpdate(data)
        .then(res => {
          console.log('update event', res);
          if (res.code == 0) {
            ToastAndroid.show('更新成功！', 3000);
            this.props.navigation.goBack({ refresh: true });
          } else {
            ToastAndroid.show(`更新失败:${res.msg}`, 3000);
            this.props.navigation.goBack({ refresh: true });
          }
          return;
        })
        .catch(e => {
          this.props.navigation.goBack({ refresh: true });
          // DeviceEventEmitter.emit(PAGENAME.ACTIVE_DETAIL, { name: 'back' });
        })
        .finally(() => {
          this.setState({ loading: false });
        });
    } else {
      // 创建
      lessonAdd({
        name: this.state.name,
        description: this.state.description,
        endTime: moment(this.state.endTime).format('YYYY-MM-DD HH:MM:SS'),
        frontCover: frontCover,
        attachment: attachment,
        delFlag: '0',
        score: Number.parseInt(this.state.score, 10),
      })
        .then(res => {
          console.log('add event', res);
          if (res.code == 0) {
            ToastAndroid.show('添加成功！', 3000);
            this.props.navigation.goBack({ refresh: true });
          } else {
            ToastAndroid.show(`添加失败:${res.msg}`, 3000);
          }
          return;
        })
        .finally(() => {
          this.setState({ loading: false });
        });
    }
    // } else {
    //   this.setState({ loading: false });
    // }
  };
  inputEndTime = (event, value) => {
    this.setState({ endTime: value });
  };
  private pickerRef: any;
  setSelectedLanguage = itemValue => {
    console.log(itemValue);
  };
  setResult = (files: any[]) => {
    console.log(files);
    this.setState({
      attachment: files[0],
    });
    // throw new Error('Function not implemented.');
  };

  handleError = (err: unknown) => {
    console.log(err);
  };

  render() {
    const { name, description, score, images, preImages, endTime } = this.state;

    return (
      // <ImageBackground
      //   source={require('../../../assets/images/bg.jpg')} // 替换为您自己的背景图路径
      //   style={{flex: 1}}
      //   imageStyle={{opacity: 0.4}} // 修改透明度，范围为0（完全透明）到1（完全不透明）
      // >
      <View>
        <Loading loading={this.state.loading} />

        <ScrollView contentContainerStyle={styles.container}>
          <Text style={style.subTitle}>标题</Text>
          <TextInput
            style={style.inputArea}
            value={name}
            onChangeText={text => this.setState({ name: text })}
          />
          <Text style={style.subTitle}>分值</Text>
          <TextInput
            style={style.inputArea}
            value={score}
            onChangeText={text => this.setState({ score: text })}
          />
          {/* <Text style={style.subTitle}>类型</Text> */}
          {/* <View
            style={{
              borderWidth: 1,
              borderColor: 'rgb(160, 160, 160)',
              borderRadius: 6,
            }}>
            <Picker
              ref={this.pickerRef}
              selectedValue={this.state.mediaType}
              onValueChange={(itemValue, itemIndex) =>
                this.setState({
                  mediaType: itemValue,
                })
              }>
              {MEDIA_TYPE.map(value => {
                return (
                  <Picker.Item
                    key={`pick-${value.value}`}
                    label={value.name}
                    value={value.value}
                  />
                );
              })}
            </Picker>
          </View> */}

          <Text style={style.subTitle}>结束时间</Text>
          <TouchableOpacity
            onPress={() => {
              DateTimePickerAndroid.open({
                value: endTime,
                onChange: this.inputEndTime,
                mode: 'date',
                is24Hour: true,
              });
            }}>
            <TextInput
              editable={false}
              style={style.inputArea}
              value={`${moment(endTime).format('YYYY-MM-DD')}`}
            />
          </TouchableOpacity>
          <Text style={style.subTitle}>描述内容</Text>
          <TextInput
            style={[style.inputArea, { height: 100 }]}
            value={description}
            onChangeText={text => this.setState({ description: text })}
            multiline
          />
          <View style={{ flexDirection: 'row' }}>
            <Text style={style.subTitle}>封面</Text>
          </View>
          <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
            {/* {preImages.map((image, index) => ( */}
            {console.log(images) || images

              ? <View style={{ position: 'relative', margin: 4 }}>
                <Image
                  source={{ uri: images.uri || `${DOMAIN_URL}${images.path}` }}
                  style={styles.image}
                />
                <TouchableOpacity
                  style={{
                    position: 'absolute',
                    top: 2,
                    right: 2,
                    backgroundColor: 'rgba(0, 0, 0, 0.5)',
                    width: 30,
                    height: 30,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    // const updatedImages = images.filter(
                    //   (value, idx) => idx !== index,
                    // );
                    this.setState({ images: null });
                  }}>
                  <DeleteIcon />

                </TouchableOpacity>
              </View>
              : <TouchableOpacity
                style={{
                  width: 75,
                  height: 75,
                  alignItems: 'center',
                  justifyContent: 'center',
                  borderWidth: 1,
                  borderColor: 'gray',
                  position: 'relative',
                  margin: 4,
                }}
                onPress={() => {
                  this.pickImage();
                }}>
                <Icon
                  name={'plus'}
                  size={50}
                  color={'rgba(0, 0, 0, 0.3)'}
                  style={{ width: 50, height: 50 }}
                />
              </TouchableOpacity>}
          </View>
          <View style={{ flexDirection: 'row' }}>
            <Text style={style.subTitle}>附件</Text>
          </View>
          <View style={{}}>
            <TouchableOpacity
              onPress={() => {
                DocumentPicker.pick({})
                  .then(v => {
                    this.setResult(v);
                  })
                  .catch(e => {
                    this.handleError(e);
                  });
              }}>
              <TextInput
                editable={false}
                style={style.inputArea}
                value={this.state.attachment && this.state.attachment.name}
              />
            </TouchableOpacity>
          </View>

          <View
            style={{
              flexDirection: 'row',
              alignSelf: 'center',
              marginVertical: 15,
            }}>
            <View style={style.pageButton}>
              <Button title="提交" onPress={() => this.submitData()} />
            </View>
          </View>
        </ScrollView>
        {/* </ImageBackground> */}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  label: {
    fontSize: 16,
    marginBottom: 5,
    fontWeight: 'bold',
  },
  input: {
    borderWidth: 1,
    borderColor: 'gray',
    borderRadius: 5,
    marginBottom: 10,
    padding: 10,
  },
  button: {
    fontSize: 16,
    color: 'blue',
    marginBottom: 10,
  },
  image: {
    width: 75,
    height: 75,
    marginBottom: 10,
  },
});

export default LessonEditScreen;
